package com.example.mmlist2.storage;

import static android.content.Context.MODE_PRIVATE;

import android.content.Context;
import android.content.SharedPreferences;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

import java.nio.charset.StandardCharsets;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;

import android.util.Base64;

public class EncryptionUtils {
    /**
     * 生成AES密钥
     *
     * @return 生成的密钥
     * @throws NoSuchAlgorithmException 如果AES算法不可用，则抛出此异常
     */
    public static SecretKey generateSecretKey() throws NoSuchAlgorithmException {
        KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
        // 设置密钥长度为128位
        keyGenerator.init(128);
        return keyGenerator.generateKey();
    }

    //加密
    public static String encrypt(String data, SecretKey secretKey) throws Exception {
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");

        // 生成一个随机的IV
        SecureRandom random = new SecureRandom();
        byte[] iv = new byte[cipher.getBlockSize()];
        random.nextBytes(iv);
        // 创建IvParameterSpec对象，用于加密时提供IV
        IvParameterSpec ivParameterSpec = new IvParameterSpec(iv);
        // 提供密钥和IV
        cipher.init(Cipher.ENCRYPT_MODE, secretKey, ivParameterSpec);
        // 将待加密的字符串转换为字节数组，并执行加密操作
        byte[] encryptedBytes = cipher.doFinal(data.getBytes(StandardCharsets.UTF_8));

        // 将IV和密文拼接在一起
        byte[] combined = new byte[iv.length + encryptedBytes.length];
        System.arraycopy(iv, 0, combined, 0, iv.length);
        System.arraycopy(encryptedBytes, 0, combined, iv.length, encryptedBytes.length);

        return Base64.encodeToString(combined, Base64.DEFAULT);
    }

    //加密密码
    public static String encryptPassword(Context context, String password) throws Exception {
        SharedPreferences sharedPreferences = context.getSharedPreferences("MyPreferences", MODE_PRIVATE);
        String encodedToken = sharedPreferences.getString("pass", null);
        byte[] decodedToken = Base64.decode(encodedToken, Base64.DEFAULT);
        SecretKey secretKey = new SecretKeySpec(decodedToken, "AES");
        return encrypt(password, secretKey);
    }

    //解密
    public static String decrypt(String encryptedData, SecretKey secretKey) throws Exception {
        // 将Base64字符串解码为字节数组
        byte[] combined = Base64.decode(encryptedData, Base64.DEFAULT);

        //指定加密模式和填充模式
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        // 分离IV和密文
        byte[] iv = new byte[cipher.getBlockSize()];
        // 从combined数组中提取IV
        System.arraycopy(combined, 0, iv, 0, iv.length);
        // 计算加密数据的长度（combined长度减去IV长度）
        byte[] encryptedBytes = new byte[combined.length - iv.length];
        // 从combined数组中提取加密数据
        System.arraycopy(combined, iv.length, encryptedBytes, 0, encryptedBytes.length);
        //提供解密时的IV
        IvParameterSpec ivParameterSpec = new IvParameterSpec(iv);
        //初始化Cipher实例，设置为解密模式，并提供密钥和IV
        cipher.init(Cipher.DECRYPT_MODE, secretKey, ivParameterSpec);
        // 执行解密操作，得到解密后的字节数组
        byte[] decryptedBytes = cipher.doFinal(encryptedBytes);

        return new String(decryptedBytes, StandardCharsets.UTF_8);
    }

    /**
     * 解密密码
     *
     * @param context           应用上下文
     * @param encryptedPassword 加密后的密码
     * @return 解密后的密码
     */
    public static String decryptPassword(Context context, String encryptedPassword) throws Exception {
        SharedPreferences sharedPreferences = context.getSharedPreferences("MyPreferences", MODE_PRIVATE);
        String encodedToken = sharedPreferences.getString("pass", null);
        byte[] decodedToken = Base64.decode(encodedToken, Base64.DEFAULT);
        SecretKey secretKey = new SecretKeySpec(decodedToken, "AES");
        return decrypt(encryptedPassword, secretKey);
    }
}
